package cn.tedu.ivos2.user.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.tedu.ivos2.base.exception.CaptchaException;
import cn.tedu.ivos2.base.exception.ServiceException;
import cn.tedu.ivos2.base.response.StatusCode;
import cn.tedu.ivos2.user.mapper.UserMapper;
import cn.tedu.ivos2.user.pojo.dto.UserLoginParam;
import cn.tedu.ivos2.user.pojo.vo.UserVO;
import cn.tedu.ivos2.user.service.UserService;
import cn.tedu.ivos2.utils.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;

/**
 * @Author: Miyako
 * @Date: 2024-08-30-17:13
 * @Description:
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    CacheUtil cacheUtil;

    @Autowired
    UserMapper userMapper;

    @Override
    public UserVO login(UserLoginParam userLoginParam) {
        String code = userLoginParam.getCode();
        //redis里查找验证码
        Serializable Captcha = cacheUtil.get("code");
        //判断验证码是否过期
        if(Captcha==null){
            throw new CaptchaException(StatusCode.DATA_UNEXISTS);
        }
        //验证码不区分大小写
        if(code.equalsIgnoreCase(String.valueOf(Captcha))) {
            String username = userLoginParam.getUsername();
            String password = userLoginParam.getPassword();
            log.debug("验证中...");
            UserVO userVO = userMapper.selectByUsername(username);
            if (userVO == null) {
                log.debug("查无此人");
                throw new ServiceException(StatusCode.USERNAME_ERROR);
            }
            if (!userVO.getPassword().equals(password)) {
                log.debug("密码错误");
                throw new ServiceException(StatusCode.PASSWORD_ERROR);
            }

            return userVO;
        }
        else {
            throw new CaptchaException(StatusCode.VALIDATE_ERROR);
        }

    }

    @Override
    public String getCaptcha() {
        //生成验证码图片，参数为 长宽,验证码数量,干扰线条数
        LineCaptcha captcha = CaptchaUtil.createLineCaptcha(100, 50, 4, 50);
        //获取验证码值
        String code = captcha.getCode();
        log.debug("验证码限时30s" + code);
        //设置30s限时的验证码存入redis
        cacheUtil.setExpire("code", (Serializable) code, 30L);
        log.debug("已存入");
        //获取用Base64编码的图片JSON字符串
        String data = captcha.getImageBase64Data();
        return data;
    }
}
